<template>
  <div class="add_box">
    <div class="add_header">
      <div class="title" @click="heandleBack">
        <img src="../../assets/image/back.jpg" class="title_icon" alt="">
        <span class="title_name">返回上一级</span>
      </div>
    </div>
    <div class="add_content">
      <a-form :model="problemState.form" ref="formRef" :rules="problemState.rules">
        <a-form-item label="问题类型" name="qsType">
          <a-select @change="changeQs" v-model:value="problemState.form.qsType" placeholder="请选择问题类型">
            <a-select-option v-for="item in problemState.qsTypeList" :key="item.id" :value="item.id">{{item.qsText}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="问题关键词" name="keyWords">
          <div class="check_list">
            <li @click="selectKeyWord(item.qsText)" :class="{'check_active':problemState.form.keyWords.includes(item.qsText)}" class="check_item" v-for="item in problemState.gjcList" :key="item.id">{{item.qsText}}</li>
          </div>
        </a-form-item>
        <a-form-item label="问题描述" placeholder="限制300个字符" name="description">
          <a-input v-model:value="problemState.form.description" type="textarea" />
        </a-form-item>

        <a-form-item label="附件" name="files">
          <a-spin :spinning="problemState.uploadLoading">
            <div>
              <a-upload :openFileDialogOnClick="false" accept=".png,.jpeg,.PNG,.JPEG" list-type="picture-card" :file-list="problemState.fileList"
              @remove="onRemove">
                <div v-if="problemState.fileList.length < 3" class="upload" @click="handleUpload">
                  <plus-outlined />
                </div>
              </a-upload>
              <p class="tips">可上传问题图片 <br>
                图片大小限制1M，限制3张</p>
            </div>
          </a-spin>
        </a-form-item>
        <a-form-item label="联系电话" name="phone">
          <a-input v-model:value="problemState.form.phone" placeholder="选填，方便我们与您联系" />
        </a-form-item>
      </a-form>
    </div>
    <div class="add_footer">
      <a-button @click="onSubmit" type="primary">提交</a-button>
      <a-button @click="heandleBack" style="margin-left: 10px">取消</a-button>
    </div>
  </div>
</template>

<script setup>

import { RollbackOutlined, PlusOutlined } from '@ant-design/icons-vue'
import column from "./js/column"
import { reactive, ref, onMounted } from 'vue'
import api from '@renderer/api/problem'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const formRef = ref();
const problemState = reactive({
  rules: column.addRules,
  form: {
    qsType: "",
    keyWords: [],
    description: "",
    phone: '',
    system2: "1",
    files: []
  },
  uploadLoading: false,
  fileList: [],
  qsTypeList:[],
  gjcList: [],
})
// 获取问题类型
const getTypeList = () => {
  window.api.fetchData(api.getQsDictionary(JSON.parse(JSON.stringify({ type: "0", system2: "4",  pageSize: 999, pageNumber: 1, system: 2 })))).then((res) => {
    if (res.code === 200) {
        problemState.qsTypeList = res.rows
      // problemState.pagination.total = res.total
    } else {
      message.error(res.data)
    }
  })
}
// 根据问题类型查询关键词
const changeQs = () => {
  problemState.form.keyWords = []
  window.api.fetchData(api.getKeyWordsByTypeId(JSON.parse(JSON.stringify({ id:problemState.form.qsType })))).then((res) => {
    if (res.code === 200) {
      console.log(333, res)
      problemState.gjcList = res.data;
    } else {
      message.error(res.data)
    }
  })
}
    // 选择关键词
    const selectKeyWord = (val) => {
      problemState.form.keyWords.find(item => item == val) ? problemState.form.keyWords = problemState.form.keyWords.filter(item => item != val) : problemState.form.keyWords.push(val);
    }
  // 监听 Loading 状态变化（来自主进程的通知）
  window.api.onLoadingChange(({ show }) => {
    problemState.uploadLoading = show
  });
// 新增
const handleUpload = async () => {
  window.api.uploadFiles(api.uploadFile({})).then(res => {
    if(res.code === 200){
      problemState.fileList.push({
        name: res.data.fileName,
        url: res.data.filePath,
        id: res.data.filePath
      })
    }
  })
}
// 删除
const onRemove = (e) => {
  console.log('选择的文件:', e);
  problemState.fileList = problemState.fileList.filter((item) => item.id !== e.id)
}
const onSubmit = () => {
  formRef.value
    .validate()
    .then(() => {

      const postData = {
        ...problemState.form,
        files:problemState.fileList.map(item => {
          console.log(item)
          return {
            fileName: item.name,
            filePath: item.url,
            fileType: item.fileType
          }
        })
      }
      postData.keyWords = postData.keyWords.join(',')
      window.api.fetchData(api.addProblem(JSON.parse(JSON.stringify(postData)))).then((res) => {
        if (res.code === 200) {
          console.log(333, res)
          message.success(res.msg)
          heandleBack()
        } else {
          message.error(res.data)
        }
      })
    })
    .catch(error => {
      console.log('error', error);
    });
};
 //     // 提交
//     submitAdd() {
//       this.$refs.formRef
//         .validate()
//         .then(() => {
//           console.log({ ...this.formState, keyWords: this.formState.keyWords.toString() })
//           api.addProblem({ ...this.formState, keyWords: this.formState.keyWords.toString() }).then(res => {
//             console.log(1111111,res)
//             if (res.code == 200) {
//               message.success('添加成功');
//               this.reset();
//               this.$router.go(-1);
//             }
//           })
//         })
//         .catch((error) => {
//           console.log('error', error);
//         });
//     },
//     //覆盖上传
//     async customRequest(info){
//         let formData = new FormData();
//         formData.append("file", info.file);
//         await api.uploadFile(formData).then(res => {
//           const resp = res.data
//           if (resp.code == '200') {
//             message.success('上传成功');
//             this.formState.files.push({
//               uid: info.file.uid,
//               fileName: resp.data.fileName,
//               filePath: resp.data.filePath,
//               fileType: resp.data.fileType
//             })
//             this.fileList.push({
//               uid: info.file.uid,
//               name: resp.data.fileName,
//               status: 'done',
//               url: resp.data.filePath
//             })
//           }
//         })
//     },

const heandleBack = () => {
  router.go(-1)
}
onMounted(() => {
  getTypeList()
})
</script>
<style lang="scss" scope>
@use './css/add.scss' as vars;
</style>
